'use strict';
angular.module('Eamclient.controllers', [])


.controller('LoginCtrl', function($scope, $state, $ionicLoading, $log, store, webq, jpushp) {
    $scope.loginData = {
        username: '',
        password: ''
    };

    $scope.doLogin = function() {
        // do a simple validate
        $ionicLoading.show({
            template: '<i class="icon ion-loading-a"></i>'
        });
        if ($scope.loginData.username && $scope.loginData.password) {
            $log.debug('loginData ' + JSON.stringify($scope.loginData));
            webq.login($scope.loginData.username, $scope.loginData.password)
                .then(function(data) {
                    /**
                     * start jpush plugin for android platform
                     */
                    jpushp.startPluginInAndroid();
                    // set alais to receive APNS messages
                    jpushp.setAlias(store.getAccessToken().username);
                    /**
                     * data is accessToken value
                     */
                    $ionicLoading.hide();
                    $state.go('tab.inspections');
                }, function(err) {
                    $ionicLoading.show({
                        template: err,
                        duration: 2000
                    });
                });
        } else {
            $ionicLoading.show({
                template: '用户名或密码不能为空。',
                duration: 2000
            });
        }
    }
})

.controller('InspectionsCtrl', function($scope, $timeout, $ionicLoading, $log, store, ntm, jpushp) {
    $scope.$root.tabsHidden = '';
    // after fetching the data from store, add dividers by sorting by 
    // date and computing the one next to neighbors
    /**
     * run on iOS
     */
    jpushp.setDebugModeFromIos();
    /**
     * run on Android
     * @type {[type]}
     */
    jpushp.startPluginInAndroid();

    var insps = _.values(store.getInspections());
    $scope.$root.inspBadgeVal = insps.length;
    var packeted_insps = eam_arrange_wo_items(insps);
    $scope.data = {
        insps: packeted_insps,
        ddvs: _.keys(packeted_insps).reverse()
    };

    $scope.$on('wo:inspection', function(event, payload) {
        // $ionicLoading.show({
        //     template: JSON.stringify(store.getInspections()),
        //     duration: 3000
        // });
        $ionicLoading.show({
            template: t('new_wo_arrival'),
            duration: 3000
        });
        var insps = _.values(store.getInspections());
        $scope.$root.inspBadgeVal = insps.length;
        var packeted_insps = eam_arrange_wo_items(insps);
        $scope.data = {
            insps: packeted_insps,
            ddvs: _.keys(packeted_insps).reverse()
        };
    });

    if ((!ntm.getNetwork())) {
        $timeout(function() {
            $ionicLoading.show({
                template: t('no_network_error'),
                duration: 3000
            });
        }, 2000);
    }

    // function _pack(metaData) {
    //     var result = {};
    //     var temp = _.sortBy(metaData, function(x) {
    //         // list by date desc order
    //         return new Date(x.eam_timestamp).getTime();
    //     });

    //     _.each(temp, function(el, index, lis) {
    //         // date divider value
    //         var ddv = (new DateFormatter).getYYYYMMDD(el.eam_timestamp);
    //         $log.debug(ddv);
    //         if (!result[ddv]) result[ddv] = [];
    //         result[ddv].push(el);
    //     });
    //     $log.debug('get result ' + JSON.stringify(result));
    //     return result;
    // }

    $scope.TrustDangerousSnippet = function(snippet) {
        return snippet;
    }
})

.controller('InspectionCtrl', function($rootScope, $scope, $stateParams, $log, $ionicPopup, $ionicModal, $ionicLoading, store, webq) {
    $scope.$root.tabsHidden = 'hide-tabs';
    var insp = store.getInspectionById($stateParams.id);
    var inspBakup = JSON.parse(JSON.stringify(insp));
    var md = window.markdownit();

    // load modals
    $ionicModal.fromTemplateUrl('templates/modal/insp-modify-toolkits.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.ModifyToolkitsModal = modal;
    });

    $ionicModal.fromTemplateUrl('templates/modal/insp-modify-parts.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.ModifyPartsModal = modal;
    });

    $scope.data = {
        title: t('inspection_wo_title').f(insp.eam_wo_id),
        showEdit: false,
        insp: insp,
        alarm_opts: [1, 2, 3, 4],
        tmp: {}
    };

    $scope.escalateInspToMaintainence = function() {
        // popup an option dialog
        var confirmPopup = $ionicPopup.confirm({
            title: t('escalate_insp_wo'),
            template: t('escalate_insp_wo_warn'),
            cancelText: t('cancel_text'),
            okText: t('ok_text')
        });
        confirmPopup.then(function(res) {
            if (res) {
                webq.escalateInspToMaintainence($scope.data.insp)
                    .then(function(result) {
                        // save data to localStorage
                        $scope.data.insp.eam_wo_status = 2;
                        store.saveInspection($scope.data.insp);
                        // update current insp user interface
                        $ionicLoading.show({
                            template: t('escalate_insp_wo_succ'),
                            duration: 3000
                        });
                    })
                    .catch(function(err) {
                        $log.error(err);
                        // alert(err);
                        $ionicLoading.show({
                            template: t('escalate_insp_wo_fail'),
                            duration: 3000
                        });
                    });
            } else {
                $log.debug('cancelled.');
            }
        });
    }

    $scope.onModifyRootCause = function() {
        // backup the pre-eam_root_cause_insp
        inspBakup.eam_root_cause_insp = $scope.data.insp.eam_root_cause_insp;
        var modifyRootCausePopup = $ionicPopup.show({
            template: '<textarea rows="8" '.concat(
                'ng-model="data.insp.eam_root_cause_insp"',
                'cols="10"> < /textarea>'
            ),
            title: t('update_root_cause'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    $scope.data.insp.eam_root_cause_insp = inspBakup.eam_root_cause_insp;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    return $scope.data.insp.eam_root_cause_insp;
                }
            }]
        });
    }

    $scope.onModifyAlarmLevel = function() {
        // An elaborate, custom popup
        var modifyAlarmLevelPopup = $ionicPopup.show({
            template: '<select style="width: 100%;!important" id="eam_alarm_level_pop"'.concat(
                ' ng-model="data.insp.eam_alarm_level"',
                ' ng-options="opt for opt in data.alarm_opts"',
                '></select>'
            ),
            title: t('update_alarm_level'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text')
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    return $scope.data.insp.eam_alarm_level;
                }
            }]
        });
    }

    $scope.onModifyToolkits = function() {
        $scope.ModifyToolkitsModal.show();
    }

    // $scope.cancelMofifyToolkits = function() {
    //     $scope.ModifyToolkitsModal.hide();
    //     $scope.data.insp.eam_maintain_toolkits = inspBakup.eam_maintain_toolkits;
    //     $rootScope.$digest();
    // }

    $scope.addNewToolkit = function() {
        delete $scope.data.tmp.newToolKitName;
        delete $scope.data.tmp.newToolKitCount;
        var newToolkitPopup = $ionicPopup.show({
            template: '<div class="list list-inset">'.concat(
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newToolKitName" type="text" placeholder="名称">',
                '</label>',
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newToolKitCount" type="number" placeholder="数量">',
                '</label>',
                '</div>'
            ),
            title: t('add_toolkit'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    delete $scope.data.tmp.newToolKitName;
                    delete $scope.data.tmp.newToolKitCount;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    if ((!$scope.data.tmp.newToolKitName) || (!$scope.data.tmp.newToolKitCount)) {
                        //don't allow the user to close unless he enters wifi password
                        e.preventDefault();
                    } else {
                        $scope.data.insp.eam_maintain_toolkits.push({
                            name: $scope.data.tmp.newToolKitName,
                            count: $scope.data.tmp.newToolKitCount,
                            footer: true,
                            icon: "/public/dummy-data/toolkit.jpg"
                        });
                        return;
                    }
                }
            }]
        });
    }


    $scope.onModifyParts = function() {
        $scope.ModifyPartsModal.show();
    }

    $scope.addNewPart = function() {
        delete $scope.data.tmp.newPartName;
        delete $scope.data.tmp.newPartCount;
        var newPartPopup = $ionicPopup.show({
            template: '<div class="list list-inset">'.concat(
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newPartName" type="text" placeholder="{0}">'.f(t('name')),
                '</label>',
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newPartCount" type="number" placeholder="{0}">'.f(t('count')),
                '</label>',
                '</div>'
            ),
            title: t('add_part'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    delete $scope.data.tmp.newPartName;
                    delete $scope.data.tmp.newPartCount;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    if ((!$scope.data.tmp.newPartName) || (!$scope.data.tmp.newPartCount)) {
                        //don't allow the user to close unless he enters wifi password
                        e.preventDefault();
                    } else {
                        $scope.data.insp.eam_maintain_parts.push({
                            name: $scope.data.tmp.newPartName,
                            count: $scope.data.tmp.newPartCount,
                            footer: true,
                            icon: "/public/dummy-data/part.png"
                        });
                        return;
                    }
                }
            }]
        });
    }

    $scope.onModifyRepairGuide = function() {
        var modifyRepairGuidePopup = $ionicPopup.show({
            template: '<textarea rows="8" '.concat(
                'ng-model="data.insp.eam_repair_guide"',
                'cols="10"> < /textarea>'
            ),
            title: t('update_repair_guide'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    $scope.data.insp.eam_repair_guide = inspBakup.eam_repair_guide;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    return $scope.data.insp.eam_repair_guide;
                }
            }]
        });
    }

    $scope.markdown = function(data) {
        return md.render(data);
    }

    $scope.countPlus = function(item) {
        item.count = item.count || 0;
        item.count++;
    };

    $scope.countMinus = function(item) {
        item.count = item.count || 0;

        if (item.count === 0) {
            return false;
        }

        item.count--;
    };

    $scope.$on('$destroy', function() {
        try {
            // do something
            $log.info('InspectionCtrl', 'onDestroy');
            $scope.ModifyToolkitsModal.remove();
            $scope.ModifyPartsModal.remove();
        } catch (e) {
            $log.error(e);
        }
    });

})

.controller('MaintenancesCtrl', function($scope, $timeout, $ionicLoading, $log, store) {
    $scope.$root.tabsHidden = '';
    // after fetching the data from store, add dividers by sorting by 
    // date and computing the one next to neighbors
    var mains = _.values(store.getMaintenances());
    $scope.$root.maintenancesBadgeVal = mains.length;
    // show a badge with current count for alarms in sliding menu
    var packeted_mains = eam_arrange_wo_items(mains);
    $scope.data = {
        mains: packeted_mains,
        ddvs: _.keys(packeted_mains).reverse()
    };

    $scope.$on('wo:maintenance', function(event, payload) {
        // $ionicLoading.show({
        //     template: JSON.stringify(store.getInspections()),
        //     duration: 3000
        // });
        $ionicLoading.show({
            template: t('new_wo_arrival'),
            duration: 3000
        });
        var mains = _.values(store.getMaintenances());
        $scope.$root.maintenancesBadgeVal = mains.length;
        // show a badge with current count for alarms in sliding menu
        var packeted_mains = eam_arrange_wo_items(mains);
        $scope.data = {
            mains: packeted_mains,
            ddvs: _.keys(packeted_mains).reverse()
        };
    });


    $scope.TrustDangerousSnippet = function(snippet) {
        return snippet;
    }
})

.controller('MaintenanceCtrl', function($rootScope, $scope, $stateParams, $log, $ionicPopup, $ionicModal, $ionicLoading, store, webq) {
    $scope.$root.tabsHidden = 'hide-tabs';
    var main = store.getMaintenanceById($stateParams.id);
    // add default value for eam_maintain_from_insp_id
    if (typeof main.eam_maintain_from_insp_id !== 'object') {
        main.eam_maintain_from_insp_id = {
            eam_wo_id: ''
        }
    }

    var mainBakup = JSON.parse(JSON.stringify(main));
    var md = window.markdownit();
    $scope.data = {
        title: t('maintain_wo_title').f(main.eam_wo_id),
        showEdit: false,
        main: main,
        alarm_opts: [1, 2, 3, 4],
        tmp: {}
    };

    $ionicModal.fromTemplateUrl('templates/modal/main-modify-toolkits.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.ModifyToolkitsModal = modal;
    });


    $ionicModal.fromTemplateUrl('templates/modal/main-modify-parts.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.ModifyPartsModal = modal;
    });


    $scope.onModifyToolkits = function() {
        $scope.ModifyToolkitsModal.show();
    }

    // $scope.cancelMofifyToolkits = function() {
    //     $scope.ModifyToolkitsModal.hide();
    //     $scope.data.insp.eam_maintain_toolkits = inspBakup.eam_maintain_toolkits;
    //     $rootScope.$digest();
    // }

    $scope.addNewToolkit = function() {
        delete $scope.data.tmp.newToolKitName;
        delete $scope.data.tmp.newToolKitCount;
        var newToolkitPopup = $ionicPopup.show({
            template: '<div class="list list-inset">'.concat(
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newToolKitName" type="text" placeholder="{0}">'.f(t('name')),
                '</label>',
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newToolKitCount" type="number" placeholder="{0}">'.f(t('count')),
                '</label>',
                '</div>'
            ),
            title: t('add_toolkit'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    delete $scope.data.tmp.newToolKitName;
                    delete $scope.data.tmp.newToolKitCount;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    if ((!$scope.data.tmp.newToolKitName) || (!$scope.data.tmp.newToolKitCount)) {
                        //don't allow the user to close unless he enters wifi password
                        e.preventDefault();
                    } else {
                        $scope.data.main.eam_maintain_toolkits.push({
                            name: $scope.data.tmp.newToolKitName,
                            count: $scope.data.tmp.newToolKitCount,
                            footer: true,
                            icon: "/public/dummy-data/toolkit.jpg"
                        });
                        return;
                    }
                }
            }]
        });
    }

    $scope.onModifyParts = function() {
        $scope.ModifyPartsModal.show();
    }

    $scope.addNewPart = function() {
        delete $scope.data.tmp.newPartName;
        delete $scope.data.tmp.newPartCount;
        var newPartPopup = $ionicPopup.show({
            template: '<div class="list list-inset">'.concat(
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newPartName" type="text" placeholder="{0}">'.f(t('name')),
                '</label>',
                ' <label class="item item-input">',
                '<input ng-model="data.tmp.newPartCount" type="number" placeholder="{0}">'.f(t('count')),
                '</label>',
                '</div>'
            ),
            title: t('add_part'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    delete $scope.data.tmp.newPartName;
                    delete $scope.data.tmp.newPartCount;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    if ((!$scope.data.tmp.newPartName) || (!$scope.data.tmp.newPartCount)) {
                        //don't allow the user to close unless he enters wifi password
                        e.preventDefault();
                    } else {
                        $scope.data.main.eam_maintain_parts.push({
                            name: $scope.data.tmp.newPartName,
                            count: $scope.data.tmp.newPartCount,
                            footer: true,
                            icon: "/public/dummy-data/part.png"
                        });
                        return;
                    }
                }
            }]
        });
    }

    $scope.onModifyAlarmLevel = function() {
        // An elaborate, custom popup
        var modifyAlarmLevelPopup = $ionicPopup.show({
            template: '<select style="width: 100%;!important" id="eam_alarm_level_pop"'.concat(
                ' ng-model="data.main.eam_alarm_level"',
                ' ng-options="opt for opt in data.alarm_opts"',
                '></select>'
            ),
            title: t('update_alarm_level'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text')
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    return $scope.data.main.eam_alarm_level;
                }
            }]
        });
    }


    $scope.onModifyRootCause = function() {
        mainBakup.eam_root_cause_maintain = $scope.data.main.eam_root_cause_maintain;
        var modifyRootCausePopup = $ionicPopup.show({
            template: '<textarea rows="8" '.concat(
                'ng-model="data.main.eam_root_cause_maintain"',
                'cols="10"> < /textarea>'
            ),
            title: t('update_root_cause'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    $scope.data.main.eam_root_cause_maintain = mainBakup.eam_root_cause_maintain;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    return $scope.data.main.eam_root_cause_maintain;
                }
            }]
        });
    }




    $scope.onModifyRepairGuide = function() {
        var modifyRepairGuidePopup = $ionicPopup.show({
            template: '<textarea rows="8" '.concat(
                'ng-model="data.main.eam_repair_guide"',
                'cols="10"> < /textarea>'
            ),
            title: t('update_repair_guide'),
            scope: $scope,
            buttons: [{
                text: t('cancel_text'),
                onTap: function(e) {
                    $scope.data.main.eam_repair_guide = mainBakup.eam_repair_guide;
                }
            }, {
                text: '<b>{0}</b>'.f(t('ok_text')),
                type: 'button-positive',
                onTap: function(e) {
                    return $scope.data.main.eam_repair_guide;
                }
            }]
        });
    }

    $scope.escalateMaintainenceToReport = function() {
        // popup an option dialog
        var confirmPopup = $ionicPopup.confirm({
            title: t('escalate_main_wo'),
            template: t('escalate_main_wo_warn'),
            cancelText: t('cancel_text'),
            okText: t('ok_text')
        });
        confirmPopup.then(function(res) {
            if (res) {
                webq.escalateMaintainenceToReport($scope.data.main)
                    .then(function(result) {
                        // save data to localStorage
                        $scope.data.main.eam_wo_status = 5;
                        store.saveMaintenance($scope.data.main);
                        // update current insp user interface
                        $ionicLoading.show({
                            template: t('escalate_main_wo_succ'),
                            duration: 3000
                        });
                    })
                    .catch(function(err) {
                        $log.error(err);
                        // alert(err);
                        $ionicLoading.show({
                            template: t('escalate_main_wo_fail'),
                            duration: 3000
                        });
                    });
            } else {
                $log.debug('cancelled.');
            }
        });
    }

    $scope.countPlus = function(item) {
        item.count = item.count || 0;
        item.count++;
    };

    $scope.countMinus = function(item) {
        item.count = item.count || 0;

        if (item.count === 0) {
            return false;
        }

        item.count--;
    };

    $scope.markdown = function(data) {
        return md.render(data);
    }

    $scope.$on('$destroy', function() {
        try {
            // do something
            $log.info('MaintenanceCtrl', 'onDestroy');
            $scope.ModifyPartsModal.remove();
            $scope.ModifyToolkitsModal.remove();
        } catch (e) {
            $log.error(e);
        }
    });


})

.controller('AccountCtrl', function($scope, $state, $log, store) {
    var profile = store.getUserProfile();
    $scope.avatarUrl = profile.avatar_url;
    $scope.name = profile.loginname;
    $scope.email = '';


    $scope.logout = function() {
        // TODO
        store.deleteAccessToken();
        $state.go('login-form');
    }

})

;
